from . import api, user
from __init__ import db, redis_store
from app.utils.status_code import RET
from flask import current_app, g, session, request, jsonify
from sqlalchemy.exc import IntegrityError
from sqlalchemy import or_, and_, desc
from app.models import User, Manager
import json
from datetime import datetime
from app.utils.token import certify_token, generate_token


@api.route("/userIsExist", methods=['POST'])
def exits_user():
    data = json.loads(request.get_data())
    username = data.get('username')
    exist = Manager.query.filter(Manager.mg_name == username).count()
    print(exist)
    if exist!=0:
        return jsonify(RET.USER_REGISTER_USER_IS_EXITS)
    else:
        return jsonify(RET.USER_REGISTER_USER_IS_NOT_EXITS)


@api.route("/register", methods=['POST'])
def register():
    data = json.loads(request.get_data())
    user = Manager()
    username = data.get('mg_name')
    user.mg_name = username
    password = data.get('mg_pwd')
    user.mg_email = data.get('mg_email')
    user.mg_mobile = data.get('mg_mobile')
    user.mg_time = datetime.now()
    user.password=password
    user.role_id = 31
    user.mg_state = 0
    if not all([username,password,user.mg_email,user.mg_mobile]):
        return jsonify(RET.USER_PARAMS_LACK)
    try:
        db.session.add(user)
        db.session.commit()
    except IntegrityError as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(RET.USER_REGISTER_USER_IS_EXITS)
    exist = Manager.query.filter(Manager.mg_name == username).first()
    if exist:
        return jsonify(RET.USER_REGISTER_SUCCESS)
    else:
        return jsonify(RET.USER_REGISTER_FAIL)


@api.route("/logout", methods=['POST'])
def logout():
    data = json.loads(request.get_data())
    username = data.get("name")
    redis_store.hset("{}_token".format(username), "token", "")
    redis_store.expire("{}_token".format(username), 1)
    session.clear()
    return jsonify(RET.USER_LOGIN_OUT)


@api.route("/login", methods=['POST'])
def login():
    data = json.loads(request.get_data())
    username = data.get('name')
    pwd = data.get("pwd")
    if not all([username, pwd]):
        return jsonify(RET.PARAMS_NOTALL)

    user = User.query.filter(User.username == username).first()
    if user:
        if user.check_pwd(pwd):
            token = generate_token(pwd, expire=60 * 60 * 3)
            # g.__setattr__
            session['token'] = token
            data = {"token": token, "code": "200"}
            # redis_store.hset("{}_token".format(username), 'token', token)
            # redis_store.expire("{}_token".format(username), RET.REDIS_TIMEOUT)
            return jsonify(data)
        return jsonify(RET.USER_LOGIN_PASSWORD_IS_ERROR)
    return jsonify(RET.USER_LOGIN_IS_NOT_EXIST)


@api.route("/managerlogin", methods=['POST'])
def managerLogin():
    data = json.loads(request.get_data())
    mg_name = data.get('name')
    mg_pwd = data.get("pwd")
    print(mg_name, mg_pwd)
    if not all([mg_pwd, mg_name]):
        return jsonify(RET.PARAMS_NOTALL)
    try:
        user = Manager.query.filter(Manager.mg_name == mg_name).first()
        if user == None:
            return jsonify(RET.USER_NAME_IS_NOTEXIST)
        if user.mg_state != 0 and user.mg_is_delete != 0:
            return jsonify(RET.USER_DISABLE)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(RET.DATABASE_ERROR)
    if user:
        if user.check_pwd(mg_pwd):
            token = generate_token(mg_pwd, expire=60 * 60 * 3)
            # g.__setattr__
            data = {"token": token, "code": "200"}
            redis_store.hset(token, 'token', mg_pwd)
            redis_store.expire(token, RET.REDIS_TIMEOUT)
            return jsonify(data)
        return jsonify(RET.USER_LOGIN_PASSWORD_IS_ERROR)
    return jsonify(RET.USER_LOGIN_IS_NOT_EXIST)
